package Classes.Components
{
	import Classes.Entity;
	import Classes.GameEvent;
	import Classes.Skill;
	import Classes.World;
	
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;

	public class AIComponent extends BaseComponent
	{
		private var m_aggroRange:Number = 0;
		private var m_isEngaged:Boolean = false;
		private var m_currentSkill:Skill;
		
		public function AIComponent(entity:Entity)
		{
			super(entity);
			m_aggroRange = getConfig().attributes['aggroRange'];
		}

		public function getConfig():Object{
			return m_entity.config.children.ai[0];
		}		
		
		override public function update(delta:int):void{
			var rbc:RigidBodyComponent = getEntity().getRigidBodyComponent();
			var ac:ActionComponent = getEntity().getActionComponent();
			
			var world:World = getWorld();
			var entity:Entity = getEntity();

			if(m_isEngaged){
				var target:Entity = ac.getTarget();
				var targetRBC:RigidBodyComponent = target.getRigidBodyComponent();
				var stopWithin:Number = 0;
				if(m_currentSkill){
					stopWithin = m_currentSkill.range
					if(!m_currentSkill.isCasting()){
						Main.actionManager.addSkillAction(m_currentSkill);
					}
				}
				
				rbc.moveTo(targetRBC.getPosition(), stopWithin);
			} else {
				var i:int;
				var players:Vector.<Entity> = rbc.getPlayersInRadius(m_aggroRange);
				var length:int = players.length;
				for(i=0;i<length;i++){
					if(testAggroRange(players[i])){
						var skill:Skill = m_entity.getSkillComponent().getSkillByName('standard_attack',players[i]);
						engage(players[i],skill);
					}
				}
			}
		}

		
		override public function destroy():void{
			super.destroy();
		}
		
		public function isEngaged():Boolean{
			return m_isEngaged;
		}

		public function engage(target:Entity, skill:Skill=null):void{
			m_isEngaged = true;
			m_currentSkill = skill;
			m_entity.getActionComponent().setTarget(target);
		}
		
		public function testAggroRange(target:Entity):Boolean{
			var aggroDistance:Number = m_entity.getRigidBodyComponent().getPosition().subtract(target.getRigidBodyComponent().getPosition()).length;
			if(aggroDistance <= m_aggroRange){
				return true;
			} else {
				return false;
			}
		}
	}
}